package com.syzg.common.controller;

import com.syzg.core.util.DateUtil;
import com.syzg.core.util.StringUtil;
import java.beans.PropertyEditorSupport;

public class CustomDateEditor extends PropertyEditorSupport
{
  private final boolean allowEmpty;

  public CustomDateEditor(boolean allowEmpty)
  {
    this.allowEmpty = allowEmpty;
  }

  public void setAsText(String text) throws IllegalArgumentException
  {
    try {
      if ((this.allowEmpty) && (StringUtil.isEmpty(text))) {
        setValue(null);
      }
      else if (text.matches("^\\d{4}-\\d{1,2}$"))
        setValue(DateUtil.parse(text, "yyyy-MM"));
      else if (text.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$"))
        setValue(DateUtil.parse(text, "yyyy-MM-dd"));
      else if (text.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$"))
        setValue(DateUtil.parse(text, "yyyy-MM-dd HH:mm"));
      else if (text.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$"))
        setValue(DateUtil.parse(text, "yyyy-MM-dd HH:mm:ss"));
      else
        throw new IllegalArgumentException("Invalid DATE value '" + text + "'");
    }
    catch (Exception e)
    {
      throw new IllegalArgumentException("Could not parse date: " + e.getMessage(), e);
    }
  }
}